from flask import Flask, jsonify, Response, request, send_from_directory
from PIL import Image, ImageDraw, ImageFont
import random, io
from flask_cors import CORS  # 添加这行导入
import random, io, os
from werkzeug.utils import secure_filename
import uuid
from datetime import datetime, timedelta
import random
import time


app = Flask(__name__)
CORS(app)  # 添加这行代码启用CORS
# app.config["UPLOAD_FOLDER"] = (
#     "D:\\project\\GitPro\\MyModel\\TEST_API\\static\\avatars"  # 头像上传目录
# )


# 提供文件访问
@app.route("/file/<filename>")
def uploaded_file(filename):
    return send_from_directory(app.config["UPLOAD_FOLDER"], filename)


# 模拟用户数据
users = [
    {
        "id": 0,
        "username": "admin",
        "password": "admin",
        "age": 25,
        "email": "alice@example.com",
        "address": "123 Main St",
        "isAdmin": 1,
        "phone": "15889231231",
        "avatar": "http://localhost:5000/file/3de3ce4f2efd422c9549031474af2553_3.jpg",
    },
    {
        "id": 1,
        "username": "Alice",
        "password": "password123",
        "age": 25,
        "email": "alice@example.com",
        "address": "123 Main St",
        "phone": "15889231231",
        "isAdmin": 0,
        "avatar": "http://localhost:5000/file/3de3ce4f2efd422c9549031474af2553_3.jpg",
    },
    {
        "id": 2,
        "username": "Bob",
        "password": "securepass",
        "age": 30,
        "email": "bob@example.com",
        "phone": "15889231231",
        "address": "456 Elm St",
        "isAdmin": 0,
        "avatar": "http://localhost:5000/file/3de3ce4f2efd422c9549031474af2553_3.jpg",
    },
    {
        "id": 3,
        "username": "Charlie",
        "password": "mypassword",
        "phone": "15889231231",
        "age": 22,
        "email": "charlie@example.com",
        "address": "789 Oak St",
        "isAdmin": 0,
        "avatar": "http://localhost:5000/file/3de3ce4f2efd422c9549031474af2553_3.jpg",
    },
]


@app.route("/hello", methods=["GET"])
def hello():
    response = {"code": 200, "message": "Hello World", "data": {"msg": "hello world"}}
    return jsonify(response)


@app.route("/users", methods=["GET"])
def get_users():
    response = {
        "code": 200,
        "message": "User data retrieved successfully",
        "data": users,
    }
    return jsonify(response)


@app.route("/getCode", methods=["GET"])
def get_code():
    code = "1234"
    width, height = 100, 40
    image = Image.new("RGB", (width, height), (255, 255, 255))
    draw = ImageDraw.Draw(image)

    try:
        font = ImageFont.truetype("arial.ttf", 24)
    except:
        font = ImageFont.load_default()

    draw.text((10, 5), code, font=font, fill=(0, 0, 0))

    for _ in range(5):
        draw.line(
            [
                (random.randint(0, width), random.randint(0, height)),
                (random.randint(0, width), random.randint(0, height)),
            ],
            fill=(
                random.randint(0, 255),
                random.randint(0, 255),
                random.randint(0, 255),
            ),
            width=2,
        )

    img_io = io.BytesIO()
    image.save(img_io, "PNG")
    img_io.seek(0)
    return Response(img_io.getvalue(), mimetype="image/png")


@app.route("/user/login", methods=["POST"])
def login():
    data = request.json
    username, password, captcha, captcha_key = (
        data.get("username"),
        data.get("password"),
        data.get("captcha"),
        data.get("captchaKey"),
    )

    if captcha != "1234":
        return jsonify({"code": 400, "message": "Invalid captcha"})

    for user in users:
        if user["username"] == username and user["password"] == password:
            return jsonify(
                {
                    "code": 200,
                    "message": "Login successful",
                    "data": {"token": str(user["id"])},
                }
            )

    return jsonify({"code": 401, "message": "Invalid username or password"})


@app.route("/user/register", methods=["POST"])
def register():
    data = request.json
    username, password, captcha, captcha_key = (
        data.get("username"),
        data.get("password"),
        data.get("captcha"),
        data.get("captchaKey"),
    )

    if captcha != "1234" or captcha_key != "myCode":
        return jsonify({"code": 400, "message": "Invalid captcha"})

    for user in users:
        if user["username"] == username:
            return jsonify({"code": 409, "message": "Username already exists"})

    users.append(
        {
            "id": len(users) + 1,
            "username": username,
            "password": password,
            "age": 0,
            "email": "",
            "address": "",
        }
    )
    return jsonify({"code": 200, "message": "Registration successful"})


@app.route("/user/info", methods=["GET"])
def get_user_detail():
    # 从请求头获取token
    user_id = request.headers.get("Authorization")
    print(user_id)
    # 查找用户
    user = next((u for u in users if str(u["id"]) == user_id), None)

    if user is None:
        return jsonify({"code": 404, "message": "User not found"})

    response = {
        "code": 200,
        "message": "User details retrieved successfully",
        "data": user,
    }
    return jsonify(response)


@app.route("/user", methods=["PUT"])
def update_user_info():
    data = request.json
    user_id = data.get("user_id")
    updated_info = data.get("updated_info")

    # 查找用户
    user = next((u for u in users if u["id"] == user_id), None)

    if user is None:
        return jsonify({"code": 404, "message": "User not found"})

    # 更新用户信息
    user.update(updated_info)

    return jsonify(
        {"code": 200, "message": "User information updated successfully", "data": user}
    )


@app.route("/user/<int:user_id>", methods=["DELETE"])
def delete_user(user_id):
    # 查找用户
    user = next((u for u in users if u["id"] == user_id), None)

    if user is None:
        return jsonify({"code": 404, "message": "User not found"})

    # 删除用户
    users.remove(user)

    return jsonify({"code": 200, "message": "User deleted successfully"})


@app.route("/user/changeAvatar", methods=["POST"])
def change_avatar():
    # 检查是否有文件上传
    if "file" not in request.files:
        return jsonify({"code": 400, "message": "No file uploaded", "data": None}), 400

    file = request.files["file"]

    # 检查文件名是否合法
    if file.filename == "":
        return jsonify({"code": 400, "message": "No selected file", "data": None}), 400

    # 检查文件类型是否允许
    # 生成安全的文件名
    filename = secure_filename(file.filename)
    # 生成唯一文件名防止冲突
    unique_filename = f"{uuid.uuid4().hex}_{filename}"
    save_path = os.path.join(app.config["UPLOAD_FOLDER"], unique_filename)

    try:
        # 保存文件
        file.save(save_path)
        # 生成完整的网络访问 URL
        avatar_url = f"http://{request.host}/file/{unique_filename}"  # 或者用 /avatars/{unique_filename}

        return jsonify(
            {
                "code": 200,
                "message": "Avatar updated successfully",
                "data": {"avatarUrl": avatar_url},
            }
        )
    except Exception as e:
        return (
            jsonify(
                {
                    "code": 500,
                    "message": f"Failed to save file: {str(e)}",
                    "data": None,
                }
            ),
            500,
        )


# 日志级别
LOG_LEVELS = ["INFO", "WARNING", "ERROR"]

# 模拟用户
USERS = ["admin", "user1", "user2", "user3", "guest"]

# 模拟操作
ACTIONS = [
    "登录系统",
    "退出登录",
    "查看仪表盘",
    "修改配置",
    "删除记录",
    "创建用户",
    "ERROR: 权限拒绝",
    "ERROR: 数据库连接失败",
    "WARNING: 密码尝试次数过多",
]


# 生成模拟日志数据
def generate_mock_logs(count=100):
    logs = []
    now = datetime.now()

    for i in range(count):
        # 随机时间（最近30天内）
        random_days = random.randint(0, 30)
        random_hours = random.randint(0, 23)
        random_minutes = random.randint(0, 59)
        random_seconds = random.randint(0, 59)

        timestamp = now - timedelta(
            days=random_days,
            hours=random_hours,
            minutes=random_minutes,
            seconds=random_seconds,
        )

        level = random.choice(LOG_LEVELS)
        username = random.choice(USERS)

        # 根据级别选择适当的操作
        if level == "ERROR":
            action = random.choice([a for a in ACTIONS if a.startswith("ERROR")])
        elif level == "WARNING":
            action = random.choice(
                [a for a in ACTIONS if a.startswith("WARNING") or "尝试" in a]
            )
        else:
            action = random.choice(
                [a for a in ACTIONS if not a.startswith(("ERROR", "WARNING"))]
            )

        details = f"这是{username}在{timestamp.strftime('%Y-%m-%d %H:%M:%S')}执行的操作详情。操作类型: {action}"

        logs.append(
            {
                "id": i + 1,
                "timestamp": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
                "username": username,
                "action": action,
                "level": level,
                "details": details,
            }
        )

    return logs


# 全局模拟数据（避免每次请求重新生成）
mock_logs = generate_mock_logs(200)


# 日志接口
@app.route("/user/logs", methods=["GET"])
def get_logs():
    # 获取查询参数
    page = int(request.args.get("page", 1))
    per_page = int(request.args.get("per_page", 20))
    level = request.args.get("level", "").split(",")  # 转为列表
    search = request.args.get("search", "").lower()
    start_time = request.args.get("start_time")
    end_time = request.args.get("end_time")

    print(level)

    # 过滤日志
    filtered_logs = mock_logs.copy()

    # 按级别过滤
    if level:
        filtered_logs = [log for log in filtered_logs if log["level"] in level]

    # 按搜索词过滤
    if search:
        filtered_logs = [
            log
            for log in filtered_logs
            if search in log["username"].lower() or search in log["action"].lower()
        ]

    # 按时间范围过滤
    if start_time and end_time:
        try:
            start_dt = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
            end_dt = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")

            filtered_logs = [
                log
                for log in filtered_logs
                if start_dt
                <= datetime.strptime(log["timestamp"], "%Y-%m-%d %H:%M:%S")
                <= end_dt
            ]
        except ValueError:
            pass

    # 分页
    total = len(filtered_logs)
    start = (page - 1) * per_page
    end = start + per_page
    paginated_logs = filtered_logs[start:end]

    return jsonify(
        {
            "code": 200,
            "message": None,
            "data": {
                "logs": paginated_logs,
                "total": total,
                "page": page,
                "per_page": per_page,
                "total_pages": (total + per_page - 1) // per_page,
            },
        }
    )


# 获取日志级别选项
@app.route("/user/log_levels", methods=["GET"])
def get_log_levels():
    return jsonify(
        {
            "code": 200,
            "message": None,
            "data": {
                "log_type": LOG_LEVELS,
            },
        }
    )


# Configuration
UPLOAD_FOLDER = "D:\\project\\GitPro\\MyModel\\TEST_API\\static\\uploads"
THUMBNAIL_FOLDER = "D:\\project\\GitPro\\MyModel\\TEST_API\\static\\uploads\\thumbnails"
ALLOWED_EXTENSIONS = {"jpg", "jpeg", "png", "gif", "webp", "mp4", "mov", "avi", "mkv"}
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["THUMBNAIL_FOLDER"] = THUMBNAIL_FOLDER
app.config["MAX_CONTENT_LENGTH"] = 100 * 1024 * 1024  # 100MB limit

# Ensure upload directories exist
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
os.makedirs(THUMBNAIL_FOLDER, exist_ok=True)


def generate_response(data=None, message="Success", code=200, error=None):
    response = {"code": code, "message": message, "data": data}
    if error:
        response["error"] = str(error)
    return jsonify(response)


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS


# Mock database
media_db = [
    {
        "id": 1,
        "name": "beach_sunset.jpg",
        "url": "/uploads/beach_sunset.jpg",
        "thumbnail": "/thumbnails/beach_sunset.jpg",
        "size": 2400000,
        "type": "image",
        "format": "jpeg",
        "created_at": "2024-01-01T10:00:00Z",
    },
    {
        "id": 2,
        "name": "party_2024.mp4",
        "url": "/uploads/party_2024.mp4",
        "thumbnail": "/thumbnails/party_2024.jpg",
        "size": 156000000,
        "type": "video",
        "format": "mp4",
        "created_at": "2024-01-02T15:30:00Z",
    },
    {
        "id": 3,
        "name": "avatar.png",
        "url": "/uploads/avatar.png",
        "thumbnail": "/thumbnails/avatar.png",
        "size": 1100000,
        "type": "image",
        "format": "png",
        "created_at": "2024-01-03T09:15:00Z",
    },
]


@app.route("/file/upload", methods=["POST"])
def upload_media():
    print("=====================================")
    print("=====================================")

    try:
        if "file" not in request.files:
            return generate_response(message="No file part", code=400)

        file = request.files["file"]
        if file.filename == "":
            return generate_response(message="No selected file", code=400)

        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file_ext = filename.rsplit(".", 1)[1].lower()

            # Save original file
            file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
            file.save(file_path)

            # For simplicity, we'll just reference the same file as thumbnail
            # In a real app, you'd generate proper thumbnails for images
            # and extract frames from videos for video thumbnails
            thumbnail_path = os.path.join(app.config["THUMBNAIL_FOLDER"], filename)

            # Create new media item
            file_type = (
                "image"
                if file_ext in {"jpg", "jpeg", "png", "gif", "webp"}
                else "video"
            )
            file_size = os.path.getsize(file_path)

            new_media = {
                "id": len(media_db) + 1,
                "name": filename,
                "url": f"/uploads/{filename}",
                "thumbnail": f"/thumbnails/{filename}",
                "size": file_size,
                "type": file_type,
                "format": file_ext,
                "created_at": datetime.utcnow().isoformat() + "Z",
            }

            media_db.append(new_media)

            return generate_response(new_media, "File uploaded successfully", 201)
        else:
            return generate_response(message="File type not allowed", code=400)
    except Exception as e:
        return generate_response(message="Error uploading file", code=500, error=e)


if __name__ == "__main__":
    app.run(debug=True)
